package com.windchime.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.windchime.blog.entity.Blog;
import com.windchime.blog.entity.Type;
import com.windchime.blog.entity.vo.BlogSearch;
import com.windchime.blog.service.BlogService;
import com.windchime.blog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class FrontIndexController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    /**
     * 首页
     * @param model 传值
     * @param page 当前页 默认为1
     * @return index
     */
    @GetMapping("/")
    public String index(Model model, @RequestParam(defaultValue = "1", value = "page") Integer page) {
        // 最热推荐
        List<Blog> hotBlogs = blogService.selectHotBlogs();
        model.addAttribute("hotBlogs", hotBlogs);

        //博文列表
        PageInfo<Blog> blogs = blogService.selectBlogList(page, 5, new BlogSearch());
        for (Blog blog : blogs.getList()) {
            blog.setTypeName(typeService.getById(blog.getTypeId()).getName());
        }
        model.addAttribute("blogs", blogs);

        return "/index";
    }

    /**
     * 搜索服务
     * @param model 传值
     * @param page 当前页
     * @param query 条件
     * @return search
     */
    @GetMapping("/search")
    public String search(Model model, @RequestParam(defaultValue = "1", value = "page") Integer page, @RequestParam String query) {
        Integer limit = 5;
        PageInfo<Blog> blogs = blogService.selectBlogListByQuery(page, limit, query);
        for (Blog blog : blogs.getList()) {
            blog.setTypeName(typeService.getById(blog.getTypeId()).getName());
        }
        model.addAttribute("blogs", blogs);
        model.addAttribute("query", query);
        return "/search";
    }

    /**
     * 页脚的信息部分
     * @param model 传值
     * @return footer
     */
    @GetMapping("/footer/blogmessage")
    public String footer(Model model) {
        List<Blog> blogs = blogService.list(new QueryWrapper<Blog>().eq("published", true));
        //文章总数--已发布的
        model.addAttribute("blogNums", blogs.size());

        //访问总数--已发布的
        Integer blogViews = 0;

        //评论总数--已发布的
        Integer blogCommentNums = 0;

        for (Blog blog : blogs) {
            Integer views = blog.getViews();
            Integer commentCount = blog.getCommentCount();
            blogViews += views;
            blogCommentNums += commentCount;
        }
        model.addAttribute("blogViews", blogViews);
        model.addAttribute("blogCommentNums", blogCommentNums);

        return "/_fragment_front :: blogMessage";
    }
}
